/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// 旋转(临时)
import { wsApi } from '@app-cad/server';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import { MathUtils } from 'three-legacy';
import { BaseCommand, CSys, Matrix3x4, Transform, Vector } from '@amcax/base';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { RJSFSchema } from '@rjsf/utils';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';

interface RotateDialogProps {
  title: string;
  onClose: () => void;
}
function RotateDialog({ title, onClose }: RotateDialogProps) {
  const [canExecute, setCanExecute] = useState(false);
  const [formData, setFormData] = useState({
    models: [],
    axis: 'Z',
    angle: 0,
  });

  useEffect(() => {
    setCanExecute(formData.models.length > 0);
  }, [formData.models]);

  // 将模型的初始位置保存起来
  const saveStartPos = () => {
    formData.models.forEach((item) => {
      item.start = item.csys.outTransformation;
      item.startCsys = CSys.origin().copy(item.csys);
    });
  };

  const getDxidList = () => {
    return formData.models.map((item) => item.idInfo.o);
  };
  const csysDeltaToTransform = (csys: CSys, csysOriginal: CSys) => {
    const delta = csys.outTransformation.combine(csysOriginal.inTransformation);
    return Transform.matrixToTransform(delta);
  };

  const doRotate = () => {
    const _angle = MathUtils.degToRad(formData.angle);
    saveStartPos();
    let normal = new Vector(0, 0, 1);
    switch (formData.axis) {
      case 'X':
        normal = new Vector(1, 0, 0);
        break;
      case 'Y':
        normal = new Vector(0, 1, 0);
        break;
      case 'Z':
        normal = new Vector(0, 0, 1);
        break;
    }
    for (const item of formData.models) {
      const center = item.csys.origin;
      const transform = new Matrix3x4().rotate(-_angle, normal, center);
      const newTransform = new Matrix3x4().multiplyMatrix3x4(
        transform,
        item.start,
      );
      item.csys.setByTransform(newTransform);
    }
  };

  const handleExecute = async () => {
    if (canExecute && formData.models.length > 0) {
      doRotate();
      await wsApi.setTransform({
        o: getDxidList(),
        transform: formData.models.map((item) =>
          csysDeltaToTransform(item.csys, item.startCsys),
        ),
      });
      onClose();
    }
  };
  //   <CommandDialog
  //     title={title}
  //     onClose={onClose}
  //     placement='topLeft'>
  //     <Box sx={{ padding: '0 10px' }}>
  //       <FormGroup>
  //         <SelectLayout>
  //           <Select title='请选择图形' />
  //         </SelectLayout>
  //         <FormControl variant='filled'>
  //           <FormLabel>选择旋转轴</FormLabel>
  //           <RadioGroup
  //             row
  //             value={axis}
  //             onChange={(_, value) => {
  //               setAxis(value as Axis);
  //             }}>
  //             <FormControlLabel
  //               value='X'
  //               control={<Radio size='small' />}
  //               label='X'
  //             />
  //             <FormControlLabel
  //               value='Y'
  //               control={<Radio size='small' />}
  //               label='Y'
  //             />
  //             <FormControlLabel
  //               value='Z'
  //               control={<Radio size='small' />}
  //               label='Z'
  //             />
  //           </RadioGroup>
  //         </FormControl>
  //         <FormControl variant='filled'>
  //           <TextField
  //             id='angle'
  //             label='旋转角度(°)'
  //             type='number'
  //             size='small'
  //             margin='dense'
  //             value={angle}
  //             inputProps={{ step: '1', min: '0', max: '360' }}
  //             onChange={(e) => {
  //               // const a = parseFloat(e.target.value)
  //               setAngle(e.target.value);
  //             }}
  //           />
  //         </FormControl>
  //         <Box
  //           sx={{
  //             padding: '5px 0',
  //             display: 'flex',
  //             justifyContent: 'flex-end',
  //           }}>
  //           <Button
  //             disabled={!canExecute}
  //             size='small'
  //             variant='contained'
  //             onClick={handleExecute}>
  //             执行
  //           </Button>
  //         </Box>
  //       </FormGroup>
  //     </Box>
  //   </CommandDialog>
  // );

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      models: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        uniqueItems: true,
        title: '[请选择图形]',
        format: PickInputRJSFFormat.MultiPickModel,
      },
      axis: {
        type: 'string',
        title: '选择旋转轴',
        enum: ['X', 'Y', 'Z'],
        default: 'Z',
      },
      angle: {
        type: 'number',
        title: '旋转角度',
        default: 0,
        format: NumberInputFormat.Angle,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={false}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        models: {
          'ui:placeholder': '请选择图形',
        },
        axis: {
          'ui:widget': 'radio',
        },
        angle: {
          'ui:placeholder': '旋转角度(°)',
        },
      }}
      submitText='完成'
      onSubmit={handleExecute}
    />
  );
}

export const cmdRotate: BaseCommand = {
  id: 'CmdRotate',
  label: 'command.rotate',
  icon: 'commands/feature/rotate',
  create: (label: string, onClose: () => void) => (
    <RotateDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};

//////////////////////////////////////////////////////////////////
